package com.powernode.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Configuration
public class PowerRouteConfig {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 针对认证请求单独的路由  获取认证成功之后的响应结果 存储在redis中
     * 便于登出以及token的校验
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder){
        return builder.routes()
                .route("auth-server-id",r->r.path("/oauth/token")
                        .filters(f->f.modifyResponseBody(String.class,String.class,((serverWebExchange, s) -> {
                            //获取响应结果 将json字符串转成json对象
                            JSONObject jsonObject = JSON.parseObject(s);
                            String accessToken = jsonObject.getString("access_token");
                            if(StringUtils.hasText(accessToken)){
                                Long expiresIn = jsonObject.getLong("expires_in");
                                stringRedisTemplate
                                        .opsForValue()
                                        .set("bearer "+accessToken," ", Duration.ofSeconds(expiresIn));
                            }
                            return Mono.just(s);
                        })))
                        .uri("lb://auth-server"))
                .build();
    }
}
